package model

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	l4g "github.com/alecthomas/log4go"
	"github.com/go-xorm/core"
	"protobuf/module/setting"
	log1 "log"
)

var engine *xorm.Engine

type XormLogger struct {
	L core.LogLevel
	S bool
}


func (x XormLogger) Debug( v ...interface{})  {
	l4g.Debug(v)
}
func (x XormLogger) Debugf(format string, v ...interface{})  {
	l4g.Debug(format , v)
}
func (x XormLogger) Error( v ...interface{})  {
	l4g.Error(v)
}
func (x XormLogger) Errorf(format string, v ...interface{})  {
	l4g.Error(format , v)
}
func (x XormLogger) Info( v ...interface{})  {
	l4g.Info(v)
}
func (x XormLogger) Infof(format string, v ...interface{})  {
	l4g.Debug(format , v)
}
func (x XormLogger) Warn( v ...interface{})  {
	l4g.Info(v)
}
func (x XormLogger) Warnf(format string, v ...interface{})  {
	l4g.Warn(format , v)
}
func (x XormLogger) Level() core.LogLevel {
	return x.L
}

func (x XormLogger) SetLevel(l core.LogLevel)  {
	x.L = l
}

func (x XormLogger) ShowSQL (show ...bool)  {
	if len(show) >= 1 {
		x.S = show [0]
	}
}

func (x XormLogger) IsShowSQL() bool {
	return x.S
}


func init()  {
	var err error
	engine , err = xorm.NewEngine("mysql", setting.DSN)
	if err != nil {
		l4g.Error(err)
	}
	engine.ShowSQL(true)
	log := XormLogger{
		S: true ,
		L:  core.LOG_DEBUG ,
	}
	engine.SetLogger(log)
	engine.SetMaxIdleConns(setting.MYSQL_POOL_MAX_ID_LE_CONN)
	engine.SetMaxOpenConns(setting.MYSQL_POOL_MAX_OPEN_CONN)
	err = engine.Ping()
	if err != nil {
		log1.Fatal("数据库连接失败: %v" , err)
	}
	l4g.Info("数据库连接成功")
}

func GetEngine() *xorm.Engine {
	return engine
}